﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;

namespace KnowFirstWebApplication
{
    public partial class _Default : basePageSessionExpire
    {
        public const string DELETE_ALERT = "למחוק קטגוריה?";
        public const string USERNAME = "UserName";
        public const string USER = "User";
        public const string CATEGORY = "Category";
        public const string SITE_NAMES_LIST = "SiteNamesList";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) //Load first category.
            {
                //Session[USERNAME] = "roeyaus";
                 btnDeleteCategory.Attributes.Add("onclick", 
                   "return confirm('" + DELETE_ALERT + "');");

                PopulateHourDayComboBoxes();
                InitCategorySettingsPage();
            }
        }

        public void PopulateHourDayComboBoxes()
        {
            System.Globalization.DateTimeFormatInfo datetimeFormat = 
                System.Globalization.DateTimeFormatInfo.CurrentInfo;
            
            cbHour.Items.Clear();
            for (int i = 0; i < 24; ++i)
            {
                cbHour.Items.Add(DateTime.MinValue.Add(TimeSpan.FromHours((double)i)).ToString("HH:mm"));
            }
            cbDay.Items.Clear();
            cbDay.DataSource = System.Globalization.DateTimeFormatInfo.CurrentInfo.DayNames;
            cbDay.DataBind();
        }

  
        public void InitCategorySettingsPage()
        {
            ClearForm();
            //Get User.
            User User = GetCurrentUser();
            DisplayUserCategoryNames(User);
            DisplayDocumentTypeList();
            DisplaySiteList();
            PopulateCbAllSites();
            ViewState[SITE_NAMES_LIST] = new List<SiteNames>();
            //Show first user category settings.
            if (User.Categories.Count > 0)
            {
                DisplayCatagorySettings(User.Categories[0]);
                ViewState[CATEGORY] = User.Categories[0].Name;
            }
        }

        public void DisplaySiteList()
        {
            //cblSites.DataSource = GetSiteNames();
            //cblSites.DataBind();
        }
        public void DisplayDocumentTypeList()
        {
            cblDocumentTypes.DataSource = Enum.GetNames(typeof(Document.Type));
            cblDocumentTypes.DataBind();
        }

        public void DisplayCatagorySettings(Category Category)
        {
            DisplayDocumentTypeList();
            DisplaySiteList();
            DisplayCategoryQueries(Category);
            DisplayDocumentTypes(Category);
            DisplayUpdateTimes(Category);
            DisplayCategorySitePriorities(Category);
            tbCategoryName.Text = Category.Name;
            tbCategoryName.Enabled = false;
            tbNewQuery.Text = string.Empty;
        }

        public void DisplayCategoryQueries(Category Category)
        {
            lbQueries.Items.Clear();
            lbQueries.DataSource = Category.Queries;
            lbQueries.DataBind();
        }

        public void DisplayCategorySitePriorities(Category Category)
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer("");
            List<SiteNames> sn = new List<SiteNames>(Category.DomainPriorities.Count);
            foreach (DomainPriority dp in Category.DomainPriorities)
            {
                
                SiteNames s = dal.GetSiteNames(dp.SiteName);

                sn.Insert(0, s);
            }
            ViewState[SITE_NAMES_LIST] = sn;
            BindReorderList();
        }

        private List<string> GetSiteNames()
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer("");
            return dal.GetAllSitesNames();
        }

        private void DisplayUserCategoryNames(User User)
        {
            lbCategories.Items.Clear();
            lbCategories.DataSource = User.Categories;
            lbCategories.DataBind();
        }

        private void DisplayDocumentTypes(Category Category)
        {
            foreach (Document.Type dt in Category.DocumentTypes)
            {
                foreach (ListItem li in cblDocumentTypes.Items)
                {
                    if (li.Value == Enum.GetName(typeof(Document.Type), dt))
                        li.Selected = true;
                }
            }
        }

        User GetCurrentUser()
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer("");
            User User = dal.GetUserByUserName(Session[USERNAME] as string);
            return User;
        }

        public void DisplayUpdateTimes(Category Category)
        {
            lbTimes.Items.Clear();
            foreach (UpdateTime ut in Category.UpdateTimes)
            {
                ListItem li = new ListItem(ut.ToString(), ((int)ut.Day).ToString());
                lbTimes.Items.Add(li);
            }
            if (Category.UpdateRealTime)
                cbRealTimeUpdates.Checked = true;
            else
                cbRealTimeUpdates.Checked = false;
        }


        public Category MakeCategoryObjectFromPageControls()
        {
            Category Category = new Category();

            if (cbRealTimeUpdates.Checked)
                Category.UpdateRealTime = true;
            else
                Category.UpdateRealTime = false;

            //Make queries list.
            List<string> QueryList = new List<string>();
            foreach (ListItem li in lbQueries.Items)
            {
                QueryList.Add(li.Value);
            }
            Category.Queries = QueryList;

            //Make UpdateTimes List.
            List<UpdateTime> utList = new List<UpdateTime>();
            foreach (ListItem li in lbTimes.Items)
            {
                utList.Add(new UpdateTime((DayOfWeek)Int32.Parse(li.Value),
                    TimeSpan.Parse(li.Text.Split(' ')[1])));
            }
            Category.UpdateTimes = utList;

            //Make Document Type List
            List<Document.Type> dtList = new List<Document.Type>();
            foreach (ListItem li in cblDocumentTypes.Items)
            {
                if (li.Selected)
                    dtList.Add((Document.Type)cblDocumentTypes.Items.IndexOf(li));
                
                    
            }
            Category.DocumentTypes = dtList;

            //Make Site priority order list.

            List<SiteNames> sn = ViewState[SITE_NAMES_LIST] as List<SiteNames>;
            List<DomainPriority> dpList = new List<DomainPriority>();

            foreach (SiteNames s in sn)
            {
                dpList.Add(new DomainPriority(s.SiteName, sn.IndexOf(s) + sn.Count));
            }

            Category.DomainPriorities = dpList;
            Category.Name = tbCategoryName.Text;
            return Category;
        }

        public void UpdateUserCategory()
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer("");
            Category Category = MakeCategoryObjectFromPageControls();
            dal.AddOrUpdateUserCategory(Session[USERNAME] as string, Category);
            InitCategorySettingsPage();
        }

        public void ClearForm()
        {

        }

        public void DeleteCategory()
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer(""); 
            dal.DeleteCategory(Session[USERNAME] as string, ViewState[CATEGORY] as string);
            
        }

        public void PopulateCbAllSites()
        {
            List<String> DisplayNames = new List<string>();
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer("");
            List<string> siteNames = dal.GetAllSitesNames();
            foreach (string name in siteNames)
            {
                SiteNames sn = dal.GetSiteNames(name);
                ListItem li = new ListItem(sn.DisplayName, sn.SiteName);
                cbAllSites.Items.Add(li);
            }

           
        }

        public void AddSiteToReorderList()
        {
            List<SiteNames> sn = ViewState[SITE_NAMES_LIST] as List<SiteNames>;
            SiteNames s = new SiteNames();
            s.DisplayName = cbAllSites.SelectedItem.Text;
            s.SiteName = cbAllSites.SelectedItem.Value;
            bool exists = false;
            foreach (SiteNames t in sn)
                if (t.SiteName == s.SiteName)
                    exists = true;
            if (!exists)
                sn.Add(s);
            ViewState[SITE_NAMES_LIST] = sn;
            BindReorderList();
        }

        public void BindReorderList()
        {
            List<SiteNames> sn = ViewState[SITE_NAMES_LIST] as List<SiteNames>;
            rlSelectedSites.DataSource = sn;
            rlSelectedSites.DataBind();
        }

        public void RemoveSiteFromReorderList()
        {

        }


        #region Events

        protected void btnLoadCategory_Click(object sender, EventArgs e)
        {
            User User = GetCurrentUser();
          
            foreach (Category cat in User.Categories)
                if (cat.Name.Equals(lbCategories.SelectedValue))
                {
                    DisplayCatagorySettings(cat);
                    ViewState[CATEGORY] = cat.Name;
                }
            //DisplayUserCategoryNames(User);
        }
        
        protected void btnAddDate_Click(object sender, EventArgs e)
        {
            UpdateTime ut = new UpdateTime((DayOfWeek)cbDay.SelectedIndex ,TimeSpan.Parse(cbHour.SelectedValue));
            if (!lbTimes.Items.Contains(new ListItem(ut.ToString())))
            {
                ListItem li = new ListItem(ut.ToString(), ((int)ut.Day).ToString());
                lbTimes.Items.Add(li);
            }
      
        }

        protected void btnRemoveDate_Click(object sender, EventArgs e)
        {
            lbTimes.Items.Remove(lbTimes.SelectedItem);
        }

        protected void btnAddQuery_Click(object sender, EventArgs e)
        {
            if (!lbQueries.Items.Contains(new ListItem(tbNewQuery.Text)))
             lbQueries.Items.Add(tbNewQuery.Text);
        }
        protected void btnRemoveQuery_Click(object sender, EventArgs e)
        {
            lbQueries.Items.Remove(tbNewQuery.Text);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            UpdateUserCategory();
        }

        protected void btnClearForm_Click(object sender, EventArgs e)
        {
            tbCategoryName.Text = string.Empty;
            lbQueries.Items.Clear();
            tbNewQuery.Text = string.Empty;
            lbTimes.Items.Clear();
            tbCategoryName.Enabled = true;
        }

        protected void btnDeleteCategory_Click(object sender, EventArgs e)
        {
            DeleteCategory();
            InitCategorySettingsPage();
        }

        protected void btnAddSite_Click(object sender, EventArgs e)
        {
            AddSiteToReorderList();
        }

        //Persist Reoder changes to viewstate SiteNames list.
        protected void rlSelectedSites_ItemReorder(object sender, AjaxControlToolkit.ReorderListItemReorderEventArgs e)
        {
            ViewState[SITE_NAMES_LIST] = (List<SiteNames>)rlSelectedSites.DataSource;
        }

        #endregion

        protected void rlSelectedSites_DeleteCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
        {
            List<SiteNames> sn = ViewState[SITE_NAMES_LIST] as List<SiteNames>;
            SiteNames toRemove = new SiteNames();
            foreach (SiteNames s in sn)
            {

                if (s.SiteName == (string)e.CommandArgument)
                {
                    toRemove = s;
                    break;
                }
            }
            sn.Remove(toRemove);
            ViewState[SITE_NAMES_LIST] = sn;
            BindReorderList();

        }

      

      

       
     

       

     

       

       

      
    }
}
